#include "Welcome.h"

#include <QtSql>
#include <QtWidgets>

#include "Connection.h"
#include "DebugTool.h"
#include "ui_Welcom.h"

// 构造函数
Welcome::Welcome(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::Welcom) {

  this->setAttribute(Qt::WA_StyledBackground, true);

  ui->setupUi(this);

  // proxyModel 初始化
  if (proxyModel == 0) {
    proxyModel = new MQSortFilterProxyModel(this);
  }

  ui->tableView->setModel (proxyModel);

  // tableView 设置编辑触发：不能触发编辑
  ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  // tableView 设置选择模式：单选
  ui->tableView->setSelectionMode (QAbstractItemView::SingleSelection);
  // tableView 设置选择行为：行选
  ui->tableView->setSelectionBehavior (QAbstractItemView::SelectRows);

  // 显示welcome的控件
  showUsers(false);


  auto *drapShadow = new QGraphicsDropShadowEffect(this);
  drapShadow->setBlurRadius(8);
  drapShadow->setOffset(3, 3);
  drapShadow->setColor(Qt::darkGreen);
  ui->welcom1->setGraphicsEffect(drapShadow);

  QStringList list;
  list << "书名"
       << "作者"
       << "出版社";
  ui->cbx_col->addItems(list);
  ui->cbx_col->setItemData(0, QString("name"));
  ui->cbx_col->setItemData(1, QString("author"));
  ui->cbx_col->setItemData(2, QString("pub"));


  ui->tableView->setAlternatingRowColors (true);
  ui->tableView_2->setAlternatingRowColors (true);

}

Welcome::~Welcome() { delete ui; }


// 显示临时的headview
void Welcome::showTempHeader()
{
  if (temp == 0) {
    temp = new QStandardItemModel(0, 8, this);
    setBookHeaderData(temp);
  }
  proxyModel->setSourceModel(temp);
  ui->tableView->setModel (proxyModel);
  ui->tableView->resizeColumnsToContents ();
  cout << temp << proxyModel;
}

void Welcome::showUsers(bool visible)
{
  ui->frm_user->setVisible (visible);
  ui->wid_user->setVisible (visible);
}

void Welcome::showWelcoms(bool visible)
{
  ui->btn_login->setVisible (visible);
  ui->btn_register->setVisible (visible);
  ui->btn_note->setVisible (visible);
}

// 成功登录后，显示用户界面
void Welcome::on_btn_login_clicked() {
  if (m_l == 0) {
    m_l = new LoginWidget;  // 登录成功，进入用户页面
    connect(m_l, &LoginWidget::login, this, &Welcome::onLogin);
  }
  m_l->show();
}


// 用户登录按钮，切换显示的控件
void Welcome::onLogin(QString str,bool admin,int loan,int max)
{
  if(admin){
    ui->lbl_userType->setText ("管理员");
    // 切换到管理员页面
    ui->stackedWidget->setCurrentIndex (1);
    ui->frm_user->setVisible(true);
    ui->tableView_2->setSortingEnabled (true);
  }
  else{
    ui->lbl_userType->setText ("用户");
    ui->lbl_loan->setText (QString::number (loan));
    ui->lbl_max->setText (QString::number (max-loan));
    showWelcoms(false);
    showUsers(true);
  }
  ui->lbl_userName->setText (str);

}



// 用户注销按钮，切换显示的控件
void Welcome::on_btn_logout_clicked()
{
  // 切换到第0页面
  ui->stackedWidget->setCurrentIndex (0);
  showWelcoms (true);
  showUsers (false);
}


// 用户须知按钮点击后显示对话框
#include "DialogNotice.h"
void Welcome::on_btn_note_clicked()
{
  DialogNotice dialog;
  dialog.exec ();
}

// 搜索按钮点击后，查询book表
void Welcome::on_btn_find_clicked()
{
  // 获取文本框字符串
    QString txt = ui->lineEdit->text();
  // 字符串为空则退出查询
    if (txt.isEmpty()) return;
  // 构造sql字符串
    QString sql;
    if (txt == "*")
      sql = QString("select * from book;");
    else
      sql = QString("select * from book where %1 like '%%2%';")
                .arg(ui->cbx_col->currentData().toString())
                .arg(txt);

  // 构造 bookModel sql模型
    if (bookModel == 0) {
      bookModel = new QSqlQueryModel(this);
    }
  // bookModel设置查询的sql语句
    bookModel->setQuery(sql);
  // bookModel 设置表头数据
    setBookHeaderData(bookModel);
  // 页面切换为 BookPage ， 表示当前查询的是book表格
    page = BookPage;
  // 代理模型设置源模型
    proxyModel->setSourceModel(bookModel);
  // 重排表格大小
    ui->tableView->resizeColumnsToContents();
}

// 在文本框输入回车，直接调用find按钮的槽函数
void Welcome::on_lineEdit_returnPressed()
{
  on_btn_find_clicked();
}


// 点击注册按钮
void Welcome::on_btn_register_clicked()
{
    if (m_r == 0) {
      m_r = new Register;
      connect(m_r, &Register::login, this, &Welcome::onLogin);
    }
    m_r->show();
}


// 点击借书按钮
void Welcome::on_btn_loan_clicked()
{
  if(page != BookPage) {
    QMessageBox::information (this,"提示","请先选择书籍");
    return;
  }

  auto *selection = ui->tableView->selectionModel ();

  if(!selection->hasSelection ()){
    QMessageBox::information (this,"提示","请先选择书籍");
    return;
  }

  int row =  selection->currentIndex ().row ();
  selection->clear ();

  // 插入loan数据表，更新user表 loan段，更新lbl_loan标签
  // 1. 取得用户名
  QString userid = ui->lbl_userName->text ();
  // 2. 取得书籍id
  QString bookid = proxyModel->data (proxyModel->index (row,0)).toString ();
  // 3. 定义sql语句
  QSqlQuery query;
  QDate date = QDate::currentDate ();
  QString sql;
  sql = QString("insert into loan values('%1','%2','%3','%4');")
            .arg (userid)
            .arg (bookid)
            .arg (date.toString ("yyyy-MM-dd"))
            .arg (date.addMonths (1).addDays (-1).toString ("yyyy-MM-dd"));

//  cout << sql;
  // 4. 执行sql
  bool ok = query.exec (sql);
  // 5. 执行不成功，提示。因为使用外键或者unique约束，返回
  if(ok == false){
    QMessageBox::information (this,"提示"," <font color='red'>未能成功借阅!</font><br/>是否已经借过此书？");
    return;
  }
  // 6. 更新user表 loan段，更新lbl_loan标签
  updateUserLoanAndUI (1);
  QString bookName = proxyModel->data(proxyModel->index(row, 2)).toString();
  QString info = QString("《%1》成功借阅").arg(bookName);
  QMessageBox::information(this, "提示", info);
}

// 点击还书按钮
void Welcome::on_btn_return_clicked()
{
  if(page != LoanPage) {
    QMessageBox::information (this,"提示","请先选择书籍");
    showLoanTable();
    return;
  }

  // 获取选择项
  auto *selection = ui->tableView->selectionModel ();

  if(!selection->hasSelection ()){
    QMessageBox::information (this,"提示","请先选择书籍");
    return;
  }

  int row =  selection->currentIndex ().row ();
  selection->clear ();  //清除选项

  // 插入loan数据表，更新user表 loan段，更新lbl_loan标签
  // 1. 取得用户名
  QString userid = ui->lbl_userName->text ();
  // 2. 取得书籍id
  QString bookid = proxyModel->data (proxyModel->index (row,1)).toString ();
  // 3. 定义sql语句
  QSqlQuery query;
  QString sql;
  sql = QString("delete from loan where book_id = '%1' AND user_id = '%2';")
            .arg (bookid)
            .arg (userid)
            ;
  bool ok = query.exec (sql);
  if(ok)
  {
    QString bookName = proxyModel->data (proxyModel->index (row,2)).toString ();
    QString info = QString("《%1》已经归还").arg (bookName);
    QMessageBox::information (this,"提示",info);
  }

  // 更新归还页面
  showLoanTable ();

  // 更新用户loan数据段
  updateUserLoanAndUI(-1);

}

// 显示借阅数据表
void Welcome::showLoanTable()
{
  // 获取用户名字符串
  QString userid = ui->lbl_userName->text();
  // 构造sql字符串  loan表中存放的是书本的ISBN，难以看懂，所以使用内接inner join 语句
   QString sql = QString("SELECT user_id, book_id, name,Loan_date,Back_date FROM loan INNER JOIN book "
      "ON loan.book_id = book.id "
      "where user_id = '%1';").arg (userid);

//  cout << sql;

  // 执行sql语句
  if(loanModel == 0){
    loanModel = new QSqlQueryModel(this);
  }

  loanModel->setQuery (sql);
  setLoanHeaderData (loanModel);
  proxyModel->setSourceModel (loanModel);
  ui->tableView->resizeColumnsToContents();
  page = LoanPage;

}

// 更新user表的loan段，lbl_loan 段
void Welcome::updateUserLoanAndUI(int book)
{
  // 更新user表的loan段，lbl_loan 段
  // 6. 更新user表 loan段，更新lbl_loan标签
  // 6.1 先获取用户的loan/max段
  QString userid = ui->lbl_userName->text();
  QString sql = QString("select loan,max from User where id =='%1';").arg(userid);
  QSqlQuery query;
  query.exec (sql);
  // 6.2 更新控件
  if(query.next ()){
    int loan = query.value (0).toInt ();
    loan += book;
    int max  = query.value (1).toInt ();
    ui->lbl_loan->setText (QString::number (loan));
    ui->lbl_max->setText (QString::number (max-loan));
    // 6.3 更新用户loan段
    sql = QString("update User set loan = %1 ;").arg(loan);
    query.exec (sql);
  }
}

void Welcome::on_btn_delay_clicked()
{
  if(page != LoanPage) {
    QMessageBox::information (this,"提示","请先选择书籍");
    showLoanTable();
    return;
  }

  // 获取选择项
  auto *selection = ui->tableView->selectionModel ();

  if(!selection->hasSelection ()){
    QMessageBox::information (this,"提示","请先选择书籍");
    return;
  }

  int row =  selection->currentIndex ().row ();
  selection->clear ();  //清除选项

  // 插入loan数据表，更新user表 loan段，更新lbl_loan标签
  // 1. 取得用户名
  QString userid = ui->lbl_userName->text ();
  // 2. 取得书籍id
  QString bookid = proxyModel->data (proxyModel->index (row,1)).toString ();

  // 3. 取得应归还的日期
  QString dateTxt = proxyModel->data (proxyModel->index (row,4)).toString ();
//  cout << dateTxt;
  QDate date = QDate::fromString (dateTxt,"yyyy-MM-dd");
  date = date.addMonths (1);
//  cout << date;

  QString sql = QString("update loan set Back_date = '%1' where book_id = '%2' And user_id = '%3' ;")
                    .arg(date.toString ("yyyy-MM-dd")).arg (bookid).arg (userid);
  QSqlQuery query;
  query.exec (sql);

  // 更新数据
  showLoanTable();
  QString bookName = proxyModel->data (proxyModel->index (row,2)).toString ();
  QString info = QString("《%1》续借成功").arg (bookName);
  QMessageBox::information (this,"提示",info);
}


// 管理员 管理用户界面
void Welcome::on_btn_man_user_clicked()
{
  if (adminTable == 0){
    adminTable = new QSqlTableModel(this);
    // 手动提交更新
    adminTable->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView_2->setModel (adminTable);
    ui->tableView_2->setSelectionBehavior (QAbstractItemView::SelectRows);
  }

  if(adminTable->isDirty ()){
    QMessageBox::information (this,"提示","页面有更新未提交");
    return;
  }

  adminTable->setTable ("user");
  adminTable->select ();
//  ui->tableView_2->resizeColumnsToContents ();
//  ui->tableView_2->horizontalHeader ()->resizeSections (QHeaderView::ResizeToContents);
}


//提交修改
void Welcome::on_bnt_admin_submit_clicked()
{
  if(adminTable==0)
    return;
  if(adminTable->isDirty ())
    adminTable->submitAll ();
}

// 撤销未提交的修改
void Welcome::on_bnt_admin_revert_clicked()
{
  if(adminTable==0)
    return;
  if(adminTable->isDirty ())
    adminTable->revertAll ();
}

// 管理图书
void Welcome::on_btn_man_book_clicked()
{
  if (adminTable == 0){
    adminTable = new QSqlTableModel(this);
    // 手动提交更新
    adminTable->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView_2->setModel (adminTable);
    ui->tableView_2->setSelectionBehavior (QAbstractItemView::SelectRows);
  }

  if(adminTable->isDirty ()){
    QMessageBox::information (this,"提示","页面有更新未提交");
    return;
  }

  adminTable->setTable ("book");
  adminTable->select ();
//  ui->tableView_2->resizeColumnsToContents ();
//  ui->tableView_2->horizontalHeader ()->resizeSections (QHeaderView::ResizeToContents);
}

// 管理借阅记录
void Welcome::on_btn_man_loan_clicked()
{
  if (adminTable == 0){
    adminTable = new QSqlTableModel(this);
    // 手动提交更新
    adminTable->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView_2->setModel (adminTable);
    ui->tableView_2->setSelectionBehavior (QAbstractItemView::SelectRows);
  }

  if(adminTable->isDirty ()){
    QMessageBox::information (this,"提示","页面有更新未提交");
    return;
  }

  adminTable->setTable ("loan");
  adminTable->select ();
//  ui->tableView_2->resizeColumnsToContents ();
//  ui->tableView_2->horizontalHeader ()->resizeSections (QHeaderView::ResizeToContents);
}

// 添加一条记录
void Welcome::on_btn_man_append_clicked()
{
  if (adminTable == 0){
    return;
  }
  QSqlRecord record = adminTable->record (adminTable->rowCount ()-1);
  adminTable->insertRecord (adminTable->rowCount (),record);
}

// 删除一条记录
void Welcome::on_btn_man_remove_clicked()
{
  if (adminTable == 0){
    return;
  }

  auto *selection = ui->tableView_2->selectionModel ();
  if(!selection->hasSelection ())
    return ;

  QModelIndexList list = selection->selectedRows ();

  for (int i = 0; i < list.count (); ++i) {
    adminTable->removeRow (list.at (i).row ());
  }

}
